<?php

namespace App\Admin\Forms;

use App\Models\Clue;
use App\Models\Tag;
use Carbon\Carbon;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;

class BatchChangeClueTagForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 处理请求
    public function handle(array $input)
    {
        // 获取外部传递参数
        if (!$tagId = data_get($input, 'tag_id'))
            return $this->response()->withValidation([
                'tag_id' => '请选择正确的标签'
            ]);
        $all = data_get($input, 'all');

        $query = Clue::query()
            ->whereNull('tag_id');
        if (!$all) {
            $end = data_get($input, 'end');
            $start = data_get($input, 'start');
            if (!validateDate($start) || !validateDate($end) || !Carbon::parse($end)->gte($start))
                return $this->response()->withValidation([
                    'start' => '请选择正确的时间'
                ]);

            $query->whereBetween('post_date', ["$start 00:00:00", "$end 23:59:59"]);
        }
        $query->update([
            'tag_id' => $tagId
        ]);


        return $this->response()->success('变更标签成功')->refresh();
    }

    public function form()
    {
        // 获取外部传递参数
        $this->radio('all', '全部')->options([
            0 => '部分',
            1 => '全部'
        ])->when([0], function () {
            $this->dateRange('start', 'end', '修改日期范围');
        })->default(1);
        $this->select('tag_id', '统一修改为')->options(Tag::toOptions())->required();
    }
}
